package com.zhouchao.email.service.impl;

import com.zhouchao.email.common.Result;
import com.zhouchao.email.service.IEmailService;
import com.zhouchao.email.task.SendTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: zhouchao
 * @Date: 2021/10/16 18:33
 * @Description:
 */
@Service
@RefreshScope
public class EmailServiceImpl implements IEmailService {

    @Autowired
    JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String fromAddress;

    private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(10);

    @Override
    public Result<Boolean> sendEmail(String email, String code) {
        try {
            // 构建一个邮件对象
            SimpleMailMessage message = new SimpleMailMessage();
            // 设置邮件主题
            message.setSubject("注册验证码");
            // 设置邮件发送者，这个跟application.yml中设置的要一致
            message.setFrom(fromAddress);
            // 设置邮件接收者，可以有多个接收者，中间用逗号隔开，以下类似
            // message.setTo("10*****16@qq.com","12****32*qq.com");
            message.setTo(email);
            // 设置邮件抄送人，可以有多个抄送人
            // message.setCc("12****32*qq.com");
            // 设置隐秘抄送人，可以有多个
            // message.setBcc("7******9@qq.com");
            // 设置邮件发送日期
            message.setSentDate(new Date());
            // 设置邮件的正文
            message.setText(code);
            // 异步发送邮件
            SendTask sendTask = new SendTask();
            sendTask.setJavaMailSender(javaMailSender);
            sendTask.setMessage(message);
            EXECUTOR_SERVICE.submit(sendTask);
        } catch (Exception e) {
            return Result.failure("500","邮件发送失败",false);
        }
        return Result.success(true);
    }
}
